package com.android.kotlincoroutinemvvmdemo.contentprovider

import android.content.ContentResolver
import android.content.ContentValues
import android.net.Uri

object StudentDBAction {

    private val URI_STUDENT_DIR =
        Uri.parse("content://${SqlConstant.AUTHORITY_STUDENT}/${SqlConstant.TABLE_STUDENT}")

    private val URI_STUDENT_ITEM =
        Uri.parse("content://${SqlConstant.AUTHORITY_STUDENT}/${SqlConstant.TABLE_STUDENT}/1")


    fun insertValue(
        resolver: ContentResolver,
        numberId: Int,
        name: String?,
        grade: String?,
        phone: String?,
        hobby: String?
    ) {
        val contentValues = ContentValues()
        contentValues.put(SqlConstant.TABLE_STUDENT_COLUMN_NUMBER_ID, numberId)
        contentValues.put(SqlConstant.TABLE_STUDENT_COLUMN_NAME, name)
        contentValues.put(SqlConstant.TABLE_STUDENT_COLUMN_GRADE, grade)
        contentValues.put(SqlConstant.TABLE_STUDENT_COLUMN_PHONE, phone)
        contentValues.put(SqlConstant.TABLE_STUDENT_COLUMN_HOBBY, hobby)
        resolver.insert(URI_STUDENT_DIR, contentValues)
    }

    fun queryValue(resolver: ContentResolver): MutableList<StudentEntity> {
        val resultList = mutableListOf<StudentEntity>()
        val cursor = resolver.query(URI_STUDENT_DIR, null, null, null, null)
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val numberId =
                    cursor.getInt(cursor.getColumnIndexOrThrow(SqlConstant.TABLE_STUDENT_COLUMN_NUMBER_ID))
                val name =
                    cursor.getString(cursor.getColumnIndexOrThrow(SqlConstant.TABLE_STUDENT_COLUMN_NAME))
                val grade =
                    cursor.getString(cursor.getColumnIndexOrThrow(SqlConstant.TABLE_STUDENT_COLUMN_GRADE))
                val phone =
                    cursor.getString(cursor.getColumnIndexOrThrow(SqlConstant.TABLE_STUDENT_COLUMN_PHONE))
                val hobby =
                    cursor.getString(cursor.getColumnIndexOrThrow(SqlConstant.TABLE_STUDENT_COLUMN_HOBBY))
                resultList.add(StudentEntity(numberId, name, grade, phone, hobby))
            }
            cursor.close()
        }
        return resultList
    }

}